package cn.chenhuanming.shh.administer.core.exception;

import cn.chenhuanming.shh.administer.exception.NotOneSelfException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.sql.SQLException;

/**
 * Created by chenhuanming on 2017-07-31.
 *
 * @author chenhuanming
 */
@ControllerAdvice(basePackages={"cn.chenhuanming.shh.administer","org.springframework.data.rest.webmvc"})
public class GlobalExceptionHandler {

    @Value("${spring.profiles.active}")
    private String profile;

    @ExceptionHandler(IllegalStateException.class)
    public ResponseEntity illegalState(IllegalStateException e){
        printException(e);
        return ResponseEntity.badRequest().body(e.getMessage());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity illegalArgument(IllegalArgumentException e){
        printException(e);
        return ResponseEntity.badRequest().body(e.getMessage());
    }

    @ExceptionHandler({NullPointerException.class, DataIntegrityViolationException.class, SQLException.class})
    public ResponseEntity unexpectedException(Exception e){
        printException(e);
        return ResponseEntity.badRequest().body("客户端参数不合法导致后台错误");
    }

    @ExceptionHandler(NotOneSelfException.class)
    public ResponseEntity NotOneException(Exception e){
        printException(e);
        return ResponseEntity.badRequest().body("非本人，不具有该操作权限");
    }

    private void printException(Exception e){
        if(profile.equals("dev"))
            e.printStackTrace();
    }
}
